<?php   
namespace app\common\model\haipi;

use think\Model;
use app\common\model\User;

class Comment extends Model {
    protected $name = 'haipi_comment';
    
    // 定义与用户表的关联
    public function user() {
        return $this->belongsTo(User::class, 'user_id', 'id');
    }
    
    // 自动类型转换
    protected $type = [
        'like' => 'json',
        'create_time' => 'datetime',
    ];
    
    // 追加字段
    protected $append = [
        'avatar_url',
        'nick_name'
    ];
    

    
    // 获取用户头像
    public function getAvatarUrlAttr($value, $data) {
        return $this->user ? full_url($this->user->avatar) : '';
    }
    
    // 获取用户昵称
    public function getNickNameAttr($value, $data) {
        $nickname = $this->user ? $this->user->nickname : '用户';
        return mb_strlen($nickname) > 7 ? mb_substr($nickname, 0, 6) . '...' : $nickname;
    }

    public function getLikeAttr($value, $data): array {
        if(empty($value)) return [];

        if(is_array ($value)){
            return $value;
        }
        return explode(',', $value);
    }

    public function setLikeAttr($value, $data) {
        if(is_array($value)){
            return implode(',', $value);
        }
        return $value;
    }
}
